import { Body, Controller, Inject, Post } from '@midwayjs/decorator';
import { UserLoginDTO } from '../dto/user.dto';
import { UserModel } from '../model/user.model';
import { JwtService } from '@midwayjs/jwt';
import MidwayConfig from '../config/config.default';
import { Validate } from '@midwayjs/validate';

@Controller('/api/admin')
export class UserController {
  @Inject()
  userModel: UserModel;
  @Inject()
  jwtService: JwtService;

  @Post('/login')
  @Validate()
  async login(@Body() userLoginDTO: UserLoginDTO) {
    const user = await this.userModel.getUserByUsernameAndPassword(
      userLoginDTO.username,
      userLoginDTO.password
    );
    if (user === null) {
      return {
        code: 400,
        result: 'error',
        message: '账号或密码不正确',
        data: null,
      };
    }
    const token = await this.jwtService.sign(
      {
        name: user.username,
        password: user.password,
      },
      MidwayConfig.jwt.secret,
      {}
    );
    return {
      code: 200,
      result: 'success',
      message: '登录成功',
      data: {
        token: token,
      },
    };
  }
}
